<template>
  <section>
    <!--工具条-->
    <el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
      <!-- :inline="true" - 行内表单 -->
      <el-form :inline="true">
        <el-form-item>
          <el-input v-model="keyword" placeholder="请输入关键字"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="keywordQuery" round><i class="el-icon-search"></i> 查询</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleAdd" round><i class="el-icon-plus"></i> 新增</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="success" @click="onsale" round><i class="el-icon-top"></i> 上架</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="warning" @click="offsale" round><i class="el-icon-bottom"></i> 下架</el-button>
        </el-form-item>
      </el-form>
    </el-col>

    <!--列表-->
    <el-table :data="products" highlight-current-row v-loading="listLoading"
              @selection-change="selsChange" style="width: 100%; font-family: 华文行楷; font-size: 20px" stripe border>
      <!-- 批量删除：type="selection - 选项 -->
      <el-table-column type="selection" width="80" align="center">
      </el-table-column>
      <el-table-column type="index" width="80" align="center">
      </el-table-column>
      <el-table-column prop="name" label="名称" width="250" align="center">
      </el-table-column>
      <el-table-column prop="resources" label="相关图片" width="200" align="center">
        <template scope="scope">
          <img :src="imgPrefix+scope.row.resources" width="100px">
        </template>
      </el-table-column>
      <el-table-column prop="saleprice" label="销售价" width="100" align="center">
      </el-table-column>
      <el-table-column prop="costprice" label="成本价" width="100" align="center">
      </el-table-column>
      <el-table-column prop="state" label="状态" width="150" sortable align="center">
        <template slot-scope="scope">
          <span style="color: green" v-if="scope.row.state==1">正常服务</span>
          <span style="color: red" v-else-if="scope.row.state==0">暂停服务</span>
        </template>
      </el-table-column>
      <el-table-column prop="offsaletime" label="下架时间" width="180" align="center">
      </el-table-column>
      <el-table-column prop="onsaletime" label="上架时间" width="180" align="center">
      </el-table-column>
      <el-table-column prop="createtime" label="创建时间" width="180" align="center">
      </el-table-column>
      <el-table-column prop="salecount" label="销售数量" width="120" align="center">
      </el-table-column>

      <el-table-column label="操作" align="center">
        <template scope="scope">
          <el-button type="success" round size="small"
                     @click="handleEdit(scope.$index, scope.row)">
            <i class="el-icon-edit"></i> 编辑</el-button><br><br>
          <el-button size="small" type="danger" round
                     @click="handleDel(scope.$index, scope.row)">
            <i class="el-icon-delete"></i> 删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!--工具条-->
    <el-col :span="24" class="toolbar">&emsp;
      <!--
        :disabled="this.sels.length===0" - 当没有选中任何选项就禁用
       -->
      <el-button type="danger" @click="batchRemove"
                 :disabled="this.sels.length===0" round>批量删除</el-button>
      <el-pagination layout="prev, pager, next" @current-change="handleCurrentChange"
                     :page-size="pageSize" :total="totals" :current-page="currentPage" style="float:right;">
      </el-pagination>
    </el-col>

    <!--添加和修改的对话框-->
    <!--
      :close-on-click-modal="false" - 点击对话外面的区域不关闭对话框
      :model="saveForm" - 绑定表单数据
      :rules="saveFormRules" - 校验规则
      ref="saveForm" - 对话框的名称 - 验证的时候需要用
      auto-complete="off" - 自动完成
    -->
    <el-dialog :title="title" :visible.sync="saveFormVisible" :close-on-click-modal="false" width="50%">
      <el-form :model="saveForm" label-width="80px" :rules="saveFormRules" ref="saveForm">
        <el-form-item label="服务名称" prop="name">
          <el-input v-model="saveForm.name" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="销售价" prop="saleprice">
          <el-input v-model="saveForm.saleprice" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="成本价" prop="costprice">
          <el-input v-model="saveForm.costprice" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="状态">
          <el-radio-group v-model="saveForm.state">
            <el-radio class="radio" :label="1">正常服务</el-radio>
            <el-radio class="radio" :label="0">暂停服务</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item prop="resources" label="服务资源">
          <el-upload class="upload-demo"
                     action="http://localhost:8080/fastDfs"
                     :on-remove="handleRemove"
                     :on-success="handleSuccess"
                     :file-list="fileList"
                     list-type="picture">
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
          </el-upload>
        </el-form-item>
        <el-form-item label="简介" prop="intro">
          <!-- v-if="saveForm.detail" 修改v-model绑定对象报错问题，v-if对需要显示的数据判断下 -->
          <quill-editor v-model="saveForm.detail.intro" v-if="saveForm.detail" :options="quillOption">
          </quill-editor>
        </el-form-item>
        <el-form-item label="预约须知" prop="orderNotice">
          <quill-editor v-model="saveForm.detail.orderNotice"  v-if="saveForm.detail"  :options="quillOption">
          </quill-editor>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="saveFormVisible = false">取消</el-button>
        <el-button type="primary" @click.native="saveSubmit" :loading="saveLoading">提交</el-button>
      </div>
    </el-dialog>

  </section>
</template>

<script>
// 引入Vue的ueditor的资源
import { quillEditor } from "vue-quill-editor"; // 调用编辑器
import 'quill/dist/quill.core.css';
import 'quill/dist/quill.snow.css';
import 'quill/dist/quill.bubble.css';
import quillConfig from '../../common/js/quill-config';
export default {
  components: {
    quillEditor
  },
  data() {
    return {
      quillOption: quillConfig,

      // 分页相关的数据
      products: [],     // 绑定到表格 - 显示列表数据 - 请求完成之后
      totals: 0,          // 总数量 - 计算分页栏 -  请求完成之
      currentPage: 1,     // 当前页 - 分页栏默认当前页显示
      pageSize: 8,        // 每页显示的条数  - 计算分页栏
      listLoading: false, // 表格上的加载框

      // 高级查询的参数
      keyword: '', // 关键字查询

      // 批量删除的数据
      sels: [],// 列表选中列 - 用于装选中的对象

      // 添加或修改的相关数据
      saveFormVisible: false,  // 对话框是否显示：默认不显示
      saveLoading: false,      // 对话框中的加载框/忙等框
      title: '',              // 标题
      saveFormRules: {        // 校验规则
        saleprice: [
          { required: true, message: '请输入销售价', trigger: 'blur' }
        ],
        costprice: [
          { required: true, message: '请输入成本价', trigger: 'blur' }
        ],
        name: [
          // 在失去焦点的时候，校验name是否为空，如果为空，就会显示红色的请输入服务的名称
          { required: true, message: '请输入服务的名称', trigger: 'blur' }
        ],
      },
      // 编辑界面数据
      saveForm: {
        id: null,
        name: '',
        costprice: 0,
        saleprice: 0,
        resources: null,
        state: 0,
        detail: {  // 与后端实体类一致
          intro: '',
          orderNotice: ''
        }
      },
      //  用于保存服务图片资源
      fileList: [],
      //图片显示的前缀：要加上http://
      imgPrefix: "http://123.207.27.208",
    }
  },
  methods: {
    // 1.分页查询：获取服务列表
    getProducts() {
      // 传递的参数
      let para = {
        // 分页参数
        currentPage: this.currentPage,
        pageSize: this.pageSize,
        // 高级查询参数 - 关键字
        keyword: this.keyword
      };
      // 页面一加载就显示加载框
      this.listLoading = true;
      this.$http.post("/product",para).then(res => {
        // 赋值总数量
        this.totals = res.data.totals;
        // 当前页的数据
        this.products = res.data.data;
        // 关闭加载框
        this.listLoading = false;
      }).catch(res => {
        this.$message.error('系统繁忙，请稍后重试！！！');
      })
    },

    // 2.点击某一页触发的方法
    handleCurrentChange(val) {
      // 当前页
      this.currentPage = val;
      this.getProducts();
    },

    // 3.关键字查询
    keywordQuery() {
      // 关键字查询从第一页开始显示
      this.currentPage = 1;
      this.getProducts();
    },

    // 4.删除
    handleDel: function (index, row) {
      this.$confirm('确认删除该记录吗?', '温馨提示', {
        type: 'warning'
      }).then(() => { // 点击确认之后要执行的代码
        // 显示加载框
        this.listLoading = true;
        // 获取id
        let id = row.id;
        this.$http.delete("/product/"+id).then(res => {
          if (res.data.success) { // 删除成功
            this.$message.success('删除成功'); // 3s自动消失

            // 如果时最后一页并且时最后一条数据的时候：当前页 = 当前页-1
            // 最后一条数据：(this.totals - 1)%this.pageSize == 0
            // 总页数：Math.ceil(this.totals/this.pageSize)
            let totalPage = Math.ceil(this.totals/this.pageSize);
            if (totalPage==this.currentPage && this.currentPage>1 && (this.totals - 1)%this.pageSize == 0) {
              this.currentPage = this.currentPage - 1;
            }

            this.getProducts();
          } else {
            this.$message.error('系统繁忙，请稍后重试【500】');
          }
          this.listLoading = false;// 关闭加载框
        }).catch(res => {
          this.$message.error('系统繁忙，请稍后重试【400,404】');
        })
      }).catch(() => { // 点击取消之后要执行的代码
      });
    },

    // 5.选项改变的时候触发
    selsChange: function (sels) {
      // 获取被选中的对象  - 集合
      this.sels = sels;
    },

    // 6.批量删除
    batchRemove: function () {
      // 获取被选中对象的id们
      let ids = this.sels.map(item => item.id); // [1,2,3]
      this.$confirm('确认删除选中记录吗？', '提示', {
        type: 'warning'
      }).then(() => {
        this.listLoading = true;
        this.$http.patch("/product",ids).then(res => {
          if (res.data.success) { // 删除成功
            this.$message.success('删除成功'); // 3s自动消失
            this.currentPage = 1;
            this.getProducts();
          } else {
            this.$message.error('系统繁忙，请稍后重试【500】');
          }
          this.listLoading = false;// 关闭加载框
        }).catch(res => {
          this.$message.error('系统繁忙，请稍后重试【400,404】');
        })
      }).catch(() => {
      });
    },

    // 7.点击添加按钮弹出对话框
    handleAdd: function () {
      this.saveForm = {
        id: null,
        name: '',
        costprice: 0,
        saleprice: 0,
        resources: null,
        state: 0,
        detail: {  // 与后端实体类一致
          intro: '',
          orderNotice: ''
        }
      };
      this.title = " 添 加 ";

      this.fileList = [];
      // 显示对话框
      this.saveFormVisible = true;
    },

    // 8.点击编辑按钮弹出对话框
    handleEdit: function (index, row) {
      // 克隆：防止对象引用修改显示的数据
      this.saveForm = Object.assign({}, row);
      this.title = " 修 改 ";
      
      // 对fileList做处理 - 因为ileList用于做回显
      this.fileList = [];
      if (this.saveForm.resources) { // 有值
        let arr = this.saveForm.resources.split(",");
        for (let i = 0; i < arr.length; i++) {
          this.fileList.push({"url":"http://123.207.27.208" + arr[i]});
        }
      }

      // 显示对话框
      this.saveFormVisible = true;
    },

    // 9.点击提交按钮添加或修改数据
    saveSubmit: function () {
      // 所有对话框中  一个名称为 saveForm的对话框  验证【上面的验证规则通过了 - 返回true，否则返回false】
      this.$refs.saveForm.validate((valid) => {
        if (valid) {
          this.$confirm('确认提交吗？', '提示', {}).then(() => {
            this.saveLoading = true;
            let para = Object.assign({}, this.saveForm);
            

            this.$http.put("/product",para).then(res => {
              if (res.data.success) {
                this.$message.success("操作成功");
                this.getProducts();
              } else {
                this.$message.error("系统繁忙，请稍后重试【500】")
              }
              this.saveLoading = false;
              this.saveFormVisible = false;
            }).catch(res => {
              this.$message.error("系统繁忙，请稍后重试【400,404】")
            })
          });
        }
      });
    },



    // 12.上传一张图片的时候会出发
    handleSuccess(response, file, fileList) {
      // { success: true, message: "操作成功", resultObj: "/group1/M00/00/0D/CgAIC2KpiEyANWQZAADIJRxVcQ8663.jpg" }
      // console.log(response);
      // 1.处理resources
      if (this.saveForm.resources) { // 有值
        this.saveForm.resources  = this.saveForm.resources + "," + response.resultObj;
      } else {
        this.saveForm.resources = response.resultObj;
      }

      // 2.处理fileList - 回显的
      //  /group1/M00/00/0D/CgAIC2KpiEyANWQZAADIJRxVcQ8663.jpg,/group1/M00/00/0D/CgAIC2KpiEyANWQZAADIJRxVcQ8663.jpg
      this.fileList = [];
      if (this.saveForm.resources) { // 有值
        let arr = this.saveForm.resources.split(",");
        for (let i = 0; i < arr.length; i++) {
          this.fileList.push({"url":"http://123.207.27.208" + arr[i]});
        }
      }
    },

    // 13.点击删除某一张图片的处理
    handleRemove: function (file, fileList) {
      // {url: "http://123.207.27.208/group1/M00/00/02/CgAIC2KevEeAX2T4AAEUusLjqqk161.png"}
      // console.log(file);
      // 1.调用删除接口删除 fastDfs上的图片
      let url = file.url
      let path = url.substring(url.indexOf("/group"));
      this.$http.delete("/fastDfs?path="+path).then(res=>{
        if (res.data.success) {
          this.$message.success("删除成功");
        } else {
          this.$message.error("删除失败");
        }
      })

      // 2.对resource做处理 ：加入path="/group1/MxVcQ8663.jpg"
      //  /group1/M00cQ8663.jpg,/group1/MxVcQ8663.jpg,/group1/MxVcQ8663.jpg
      if (this.saveForm.resources) { // 只有值
        // ["/group1/M00cQ8663.jpg","/group1/MxVcQ8663.jpg","/group1/MxVcQ8663.jpg"]
        let arr = this.saveForm.resources.split(",");
        for (let i = 0; i < arr.length; i++) {
          if (arr[i] == path) {
            // 从i开始删除，向后删除1个
            arr.splice(i,1);
            break;
          }
        }
        this.saveForm.resources = arr.join(","); //  /group1/M00cQ8663.jpg,/group1/MxVcQ8663.jpg
      }

      // 3.对fileList做处理
      this.fileList = [];
      if (this.saveForm.resources) { // 有值
        let arr = this.saveForm.resources.split(",");
        for (let i = 0; i < arr.length; i++) {
          this.fileList.push({"url":"http://123.207.27.208" + arr[i]});
        }
      }
    },

    // 14.上架
    onsale() {
      // 获取选中的id
      var ids = this.sels.map(item => item.id);
      if (! ids || ids.length < 1) {
        this.$message.error("请至少选择一条数据！！！");
        return;
      }

      this.$confirm('确认上架该服务吗？', '提示', {
        type: 'warning'
      }).then(() => { // 点击了确定
        this.$http.patch("/product/onsale",ids).then(res => {
          if (res.data.success) {
            this.$message.success("上架成功！！！");
            this.getProducts();
          } else {
            this.$message.error(res.data.message + "系统异常，请稍后重试！！！【500】");
          }
        }).catch(res => {
          this.$message.error("系统异常，请稍后重试！！！【400，404】");
        })
      }).catch(() => { // 点了取消
      });
    },

    // 15.下架
    offsale() {
      var ids = this.sels.map(item => item.id);
      if (! ids || ids.length < 1) {
        this.$message.error("请至少选择一条数据！！！");
        return;
      }
      this.$confirm('确认下架该服务吗？', '提示', {
        type: 'warning'
      }).then(() => { // 点击了确定
        this.$http.patch("/product/offsale",ids).then(res => {
          if (res.data.success) {
            this.$message.success("下架成功！！！");
            this.getProducts();
          } else {
            this.$message.error("系统异常，请稍后重试！！！【500】");
          }
        }).catch(res => {
          this.$message.error("系统异常，请稍后重试！！！【400，404】");
        })
      }).catch(() => { // 点了取消
      });
    }

  },
  mounted() {
    this.getProducts();
  }
}

</script>

<style scoped>
</style>